﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Web.Mvc;
using MvcContrib.FluentHtml;
using MvcContrib.UI.InputBuilder.Helpers;
using Peak.Core;
using Peak.Resources;
using Peak.Web.Controllers.Services;
using SharpArch.Core;
using System.Linq.Expressions;

namespace Peak.Web.Controllers.HtmlExtentions
{
  public static class UsersListExtension
  {
    public static MvcHtmlString UsersList<T>(this IViewModelContainer<T> html, Expression<Func<T, object>> action) 
      where T:class 
    {
      object obj = action.Compile()(html.ViewModel);
      string assignedTo = null;
      if (obj != null)
        assignedTo = obj.ToString();

      ISessionService sessionService = ServiceLocator.Current.GetInstance<ISessionService>();
      List<SelectListItem> list = new List<SelectListItem>();
      list.Add(new SelectListItem() { Selected = assignedTo == null, Text = Labels.NotSelected, Value = "" });
      list.Add(new SelectListItem() { Selected = assignedTo == Thread.CurrentPrincipal.Identity.Name, Text = Labels.Me, Value = Thread.CurrentPrincipal.Identity.Name });              
      foreach (User user in sessionService.Project.Users.OrderBy(f=>f.UserName))
      {
        if (user.UserName != Thread.CurrentPrincipal.Identity.Name)
          list.Add(new SelectListItem() {Selected = user.UserName == assignedTo, Text = user.UserName, Value = user.UserName});                
      }
      return html.Html.DropDownList(ReflectionHelper.BuildNameFrom(action), list);  
    }
  }
}
